package com.taotao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.taotao.common.enums.FloorType;
import com.taotao.mapper.*;
import com.taotao.pojo.*;
import com.taotao.service.PictureService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.DateUtil;
import com.taotao.mapperCust.CommonMapperCust;
import com.taotao.service.MessageInfoService;
import com.taotao.service.ParamService;

@Service
public class MessageInfoServiceImpl implements MessageInfoService{
	
	BaseResult baseResult = new BaseResult();
	@Autowired
	EySessionInfoMapper eySessionInfoMapper;
	@Autowired
	EyMessageInfoMapper eyMessageInfoMapper;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyServiceMapper eyServiceMapper;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	CommonMapperCust commonMapperCust;
	@Autowired
	EyOrderMapper eyOrderMapper;
	@Autowired
	EyAddressMapper eyAddressMapper;
	@Autowired
	ParamService paramService;
	@Autowired
	PictureService pictureService;
	@Autowired
	EyTransferMapper eyTransferMapper;
	@Override
	public Map<String, Object> loadMessage(Map<String, String> map) {
		try {
			String pageNum =  map.get("pageNum");
			String pageSize = map.get("pageSize");
			String sessionKey =  map.get("sessionKey");
			String memberId =  map.get("memberId");
			
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);

			List<Map> messageList =new ArrayList<>();
			if(StringUtils.isNotBlank(sessionKey)){
				Map<String,String> paramMap=new HashMap<String,String>();
				paramMap.put("orderBy", " id desc ");
				paramMap.put("sessionKey",sessionKey);
				PageHelper.startPage(num,size);
				messageList = commonMapperCust.queryMessageList(paramMap);
		  		
		  		String endTime="";
		  		String startTime="";
				String tencentCosEnable=paramService.getParam(Constants.tencent_cos_enable);
		  		for(int i=0;i<messageList.size();i++){
		  			Map m = messageList.get(i);
		  			String msgType =String.valueOf(m.get("msgType"));
					String orderId = String.valueOf(m.get("orderId"));
					if(Constants.num_2.equals(msgType)){ //聊天内容是图片
						String imageUrl=String.valueOf(m.get("content"));
						if(Constants.false_string.equals(tencentCosEnable)) {
							imageUrl=pictureService.changeDomain(imageUrl);
						}
						m.put("content",imageUrl);
					}

					if(Constants.num_3.equals(msgType)){ //聊天内容是位置
						String content=String.valueOf(m.get("content"));
						m.put("content", JSONObject.parse(content));
					}

					if(Constants.num_7.equals(msgType)){ //聊天内容是转账
						String transferId=String.valueOf(m.get("content"));
						EyTransfer transfer = eyTransferMapper.selectByPrimaryKey(Integer.parseInt(transferId));
						m.put("transfer", transfer);
					}

					if(Constants.num_5.equals(msgType)){ //goods类确认订单
						EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
						m.put("order", order);
						Integer goodsId = order.getGoodsId();
						EyGoods goods = eyGoodsMapper.selectByPrimaryKey(goodsId);
						m.put("goods", goods);
		  				Integer addressId = order.getAddressId();
		  				EyAddress address = eyAddressMapper.selectByPrimaryKey(addressId);
		  				m.put("address", address);
		  			}else if(Constants.num_6.equals(msgType)){//service类确认订单
						if(StringUtils.isBlank(orderId)) { //orderId空后面解析会报错，为啥为空，页面未支付却走了支付成功的回调bug
							messageList.remove(m);
							continue;
						}
						EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
						m.put("order", order);
						Integer serviceId=order.getServiceId();
						EyService service = eyServiceMapper.selectByPrimaryKey(serviceId);
						m.put("service", service);
						Integer addressId=service.getAddressId();
						EyAddress address = eyAddressMapper.selectByPrimaryKey(addressId);
						m.put("address", address);
						if(Constants.num_1.equals(service.getServiceType())){ //搬家类 ToAddress
							service.setFloor(FloorType.getValue(service.getFloor()));
							service.setFloor2(FloorType.getValue(service.getFloor2()));

							Integer addressId2=service.getAddressId2();
							EyAddress address2 = eyAddressMapper.selectByPrimaryKey(addressId2);
							m.put("address2", address2);
						}
					}

					String createTime =String.valueOf(m.get("createTime"));
					if(StringUtils.isBlank(endTime)){
						endTime=createTime;
					}else{
						startTime=createTime;
						long seconds = DateUtil.getSeconds(startTime,endTime);
						if(seconds<3600){
							m.put("createTime", " ");
							continue;
						}
						endTime=createTime;
					}
					String language = paramService.getParam("language");
					String updateTime=DateUtil.fromToday(DateUtil.strToDate(createTime), language);
					m.put("createTime",updateTime);
				}
			}

			PageInfo<Map> pageInfo = new PageInfo<>(messageList);
	  		return baseResult.getSuccMap(pageInfo);
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
		
	}

	@Override
	public Map<String, Object> processMessage(String sender, String receiver, String content, String modeType,String msgType,
			String serviceName,String id,boolean online,String sessionKey,String orderId) {
		try {
			String isRead="0";
			EySessionInfo senderSession = null;
			EySessionInfo receiverSession = null;
			if(StringUtils.isBlank(sessionKey)){
				senderSession = this.getSessoinInfo(sender,receiver,id,modeType,msgType,serviceName,"");
				receiverSession = this.getSessoinInfo(receiver,sender,id,modeType,msgType,serviceName,"");
			}else{
				senderSession = this.getSessoinInfo("",receiver,id,modeType,msgType,serviceName,sessionKey);
				receiverSession = this.getSessoinInfo(receiver,"",id,modeType,msgType,serviceName,sessionKey);
				//发送者是管理员的话，sender取原来会话的发送者
				sender=senderSession!=null?String.valueOf(senderSession.getSender()):String.valueOf(receiverSession.getReceiver()); 
			}
			
			if(senderSession==null && receiverSession==null){  //创建两通会话
				String dateAndTime = DateUtil.getDateAndTime();
				sessionKey=dateAndTime+id+sender+receiver;
				this.insertSessionInfo(sender,receiver,content,id,sessionKey,isRead,modeType,msgType,serviceName);  //创建发送者会话 未读
				this.insertSessionInfo(receiver,sender,content,id,sessionKey,"1",modeType,msgType,serviceName);  //创建接受者会话 已读
				
			}else if(senderSession!=null && receiverSession!=null){
				sessionKey=senderSession.getSessionKey();
				senderSession.setModeType(modeType);
				senderSession.setMsgType(msgType);
				senderSession.setContent(content);
				senderSession.setIsRead(isRead); //未读
				senderSession.setStatus(Constants.num_1); //正常状态
				senderSession.setUpdateTime(DateUtil.getDateAndTime());
				receiverSession.setModeType(modeType);
				receiverSession.setMsgType(msgType);
				receiverSession.setContent(content);
				receiverSession.setIsRead("1"); //已读
				receiverSession.setStatus(Constants.num_1); //正常状态
				if("goods".equals(modeType)){
					receiverSession.setGoodsId(Integer.parseInt(id));
				}else if("service".equals(modeType)){
					receiverSession.setServiceName(serviceName);
				}else if("robot".equals(modeType)){
					receiverSession.setGoodsId(Integer.parseInt(id));
				}
				receiverSession.setUpdateTime(DateUtil.getDateAndTime());
				eySessionInfoMapper.updateByPrimaryKeySelective(senderSession);
				eySessionInfoMapper.updateByPrimaryKeySelective(receiverSession);
			}else {
				if(senderSession!=null){
					sessionKey=senderSession.getSessionKey();
					this.insertSessionInfo(receiver,sender,content,id,sessionKey,"1",modeType,msgType,serviceName);  //创建接受者会话
				}else if(receiverSession!=null){
					sessionKey=receiverSession.getSessionKey();
					this.insertSessionInfo(sender,receiver,content,id,sessionKey,isRead,modeType,msgType,serviceName);  //创建发送者会话
				}
			}

			EyMessageInfo m=new EyMessageInfo();
			String defaultMsg = paramService.getParam("default_msg");
			if(defaultMsg.equalsIgnoreCase(content)) {
				//default_msg 竖线分割多条发送多条消息
				String[] contentSplit = content.split("\\|");
				for (String c : contentSplit) {
					content=c;
					this.insertMessageInfo(m,sender,receiver,content,modeType,msgType,online,sessionKey,orderId);
				}
			}else{
				this.insertMessageInfo(m,sender,receiver,content,modeType,msgType,online,sessionKey,orderId);
			}

			HashMap<String,String> map=new HashMap<>();
			map.put("sessionKey", sessionKey);
			map.put("sender", sender);
			map.put("messageId", String.valueOf(m.getId()));
			return baseResult.getSuccMap(map);
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}

	private void insertMessageInfo(EyMessageInfo m,String sender, String receiver, String content, String modeType,String msgType, boolean online,
			String sessionKey,String orderId) {
			m.setSessionKey(sessionKey);
			if(StringUtils.isNotBlank(orderId) && !Constants.String_null.equals(orderId)){
				m.setOrderId(Integer.parseInt(orderId));
			}
			m.setSender(Integer.parseInt(sender));
			m.setReceiver(Integer.parseInt(receiver));
			m.setContent(content);
			m.setModeType(modeType);
			m.setMsgType(msgType);
			m.setCreateTime(DateUtil.getDateAndTime());
			eyMessageInfoMapper.insert(m);
		
	}

	private void insertSessionInfo(String sender, String receiver, String content, String id,String sessionKey,String isRead,
			String modeType,String msgType,String serviceName) {
			EySessionInfo s=new EySessionInfo();
			if("goods".equals(modeType)){
				s.setGoodsId(Integer.parseInt(id));
			}else if("service".equals(modeType)){
				s.setServiceId(Integer.parseInt(id));
				s.setServiceName(serviceName);
			}else if("robot".equals(modeType)){
				s.setGoodsId(Integer.parseInt(id));
			}else if("report".equals(modeType)){
				s.setGoodsId(Integer.parseInt(id));
			}
			s.setSender(Integer.parseInt(sender));
			s.setReceiver(Integer.parseInt(receiver));
			s.setModeType(modeType);
			s.setMsgType(msgType);
			s.setContent(content);
			s.setSessionKey(sessionKey);
			s.setIsRead(isRead);
			s.setStatus(Constants.num_1); //正常状态
			s.setCreateTime(DateUtil.getDateAndTime());
			s.setUpdateTime(DateUtil.getDateAndTime());
			eySessionInfoMapper.insert(s);  
		
	}

	private EySessionInfo getSessoinInfo(String sender, String receiver, String id,
			String modeType,String msgType,String serviceName,String sessionKey) {
			EySessionInfoExample example = new EySessionInfoExample();
			com.taotao.pojo.EySessionInfoExample.Criteria criteria = example.createCriteria();
			if(StringUtils.isNotBlank(sender)){
				criteria.andSenderEqualTo(Integer.parseInt(sender));
			}
			if(StringUtils.isNotBlank(receiver)){
				criteria.andReceiverEqualTo(Integer.parseInt(receiver));
			}
			if(StringUtils.isNotBlank(sessionKey)){
				criteria.andSessionKeyEqualTo(sessionKey);
			}
			
			if("goods".equals(modeType)){
				criteria.andGoodsIdEqualTo(Integer.parseInt(id));
			}else if("service".equals(modeType)){ //同一个人多次申请，使用原来的会话
				criteria.andServiceIdEqualTo(Integer.parseInt(id));
			}else if("robot".equals(modeType)){
				criteria.andGoodsIdEqualTo(Integer.parseInt(id));
			}else if("report".equals(modeType)){
				criteria.andGoodsIdEqualTo(Integer.parseInt(id));
			}

	  		List<EySessionInfo> list = eySessionInfoMapper.selectByExample(example);
	  		if(list!=null && list.size()>0){
	  			return list.get(0);
	  		}
	  		return null;
	}

	@Override
	public Map<String, Object> queryMessageList(Map<String, String> map) {
		try {
			String pageNum =  map.get("pageNum");
			String pageSize = map.get("pageSize");
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);
	  		PageHelper.startPage(num,size);
			List<Map> list = commonMapperCust.queryMessageList(map);
			for(Map m:list){
				String createTime=String.valueOf(m.get("createTime"));
				createTime=DateUtil.getDateTimeFormatStr(createTime);
				m.put("createTime", createTime);
			}
			
			PageInfo<Map> pageInfo = new PageInfo<>(list);
	  		return baseResult.getSuccMap(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}
}
